package dao;

import java.util.List;
import models.Page;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * This Dao is for the static pages on the site; Here are all the finders
 * presented where you can get all the pages or a specific one.
 *
 * @author Sander
 */
public class PageDao {

    private final Session session;

    public PageDao(Session session) {
        this.session = session;
    }

    /**
     * Searches for all the pages and returns them in a list.
     *
     * @return
     */
    public List<Page> findAll() {
        Transaction tx = session.beginTransaction();
        List<Page> list = session.createQuery("from Page ORDER BY id ASC").list();
        tx.commit();
        return list;
    }

    /**
     * Searches a page with the given title and returns it in a list.
     *
     * @param title
     * @return
     */
    public List<Page> findPageByTitle(String title) {
        Transaction tx = session.beginTransaction();
        title = title.replace("_", " ");
        List<Page> list = session.createQuery("from Page where title = :title ORDER BY id ASC").setParameter("title", title).list();
        tx.commit();
        return list;
    }

    public boolean save(Page page) {
        try {
            Transaction tx = session.beginTransaction();
            session.save(page);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public boolean update(Page page) {
        try {
            Transaction tx = session.beginTransaction();
            session.update(page);
            tx.commit();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public void delete(Page page) {
        Transaction tx = session.beginTransaction();
        session.delete(page);
        tx.commit();
    }

    public Page get(long id) {
        return (Page) session.get(Page.class, id);
    }
}
